// dataGrouper.js
import { generateTimeIntervals } from './timeUtil.js';

export function groupAllDataByTimeInterval(data) {
  const groupedData = {};

  data.forEach(item => {
    const itemDate = new Date(item.createdAt);
    const dateKey = `${itemDate.getFullYear()}-${itemDate.getMonth() + 1}-${itemDate.getDate()}`;

    if (!groupedData[dateKey]) {
      groupedData[dateKey] = [];
    }

    const itemTime = itemDate.getTime();
    const intervals = generateTimeIntervals(itemDate);

    for (let i = 0; i < intervals.length - 1; i++) {
      const intervalStart = intervals[i];
      const intervalEnd = intervals[i + 1];
      const intervalStartTime = intervalStart.getTime();
      const intervalEndTime = intervalEnd.getTime();

      if (itemTime >= intervalStartTime && itemTime < intervalEndTime) {
        const intervalKey = `${intervalStart.getHours()}:${intervalStart.getMinutes().toString().padStart(2, '0')}-${intervalEnd.getHours()}:${intervalEnd.getMinutes().toString().padStart(2, '0')}`;
        const groupKey = `${dateKey} ${intervalKey}`;

        if (!groupedData[groupKey]) {
          groupedData[groupKey] = {
            date: dateKey,
            interval: intervalKey,
            items: []
          };
        }

        groupedData[groupKey].items.push(item);
        break;
      }
    }
  });
  // console.log('Grouping Data:', data);
  // return Object.values(groupedData);
    // 过滤掉空组
  return Object.values(groupedData).filter(group => group.items && group.items.length > 0);
}